import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, ScrollView, Image, Slider } from '@tarojs/components'
import { SDBody, SDLoading } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import CommonEmptyView from '../../../comps/empty-view'

import PageProps from '../../../redux'
import { login, logout } from '../../../redux/actions'

import SearchIcon from '../../../images/ic_search_black.png'
import PlayIcon from '../../../images/ic_play.png'
import VideoIcon from '../../../images/ic_voice.png'
import EmptyIcon from '../../../images/ic_nothing_search.png'

import './index.less'

type PageState = {
  tabBarList: any[],
  scrollLeft: number,
  mainIsLoading: boolean,

  hasData: boolean,
  hasMore: boolean,
  loading: boolean,
  hideLoading: boolean,
  dataList: any[],
}

type PageOwnProps = {}

interface TabBarDiscoverPage {
  props: PageProps & PageOwnProps
}

const { windowWidth } = Taro.getSystemInfoSync()

@connect(({userState}) => ({
  userState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  }
}))
class TabBarDiscoverPage extends Component<PageOwnProps, PageState> {

  constructor () {
    super()
    this.state = {
      tabBarList: [
      ],
      scrollLeft: 0,
      mainIsLoading: true,
      hasData: true,
      hasMore: true,
      loading: false,
      hideLoading: false,
      dataList: []
    }
  }

  config: Config = {
    navigationBarTitleText: '发现',
    enablePullDownRefresh: true
  }

  tabBarRequestTask: any | undefined = undefined

  articleRequestTask: any | undefined = undefined

  currentGroupCode: string | undefined = undefined

  render () {

    const { tabBarList, scrollLeft, mainIsLoading, loading, hasMore, hasData, hideLoading, dataList } = this.state

    return (
      <SDBody sd-class='container' loading={mainIsLoading} showPadding={false}>
        {
          tabBarList.length > 0 ? (
            <View className="menu-bar border-bottom_1px">
              <ScrollView id='menu-bar_ID' className="scroll-left" scrollX scrollWithAnimation scrollLeft={scrollLeft}>
                {
                  tabBarList.map((item, index) => {
                    return (
                      <View id={`tabBar-index${index}`} className={`left-item ${item.selected ? 'left-item_sel' : ''}`} key={index} onClick={this.switchTabBarIndex.bind(this, index)}>
                        <View className="inner-item">
                          <View className="title">{item.title}</View>
                          <View className="line" />
                        </View>
                      </View>
                    )
                  })
                }
              </ScrollView>
              <View className="right" onClick={this.gotoSearchPage}>
                <Image className="search-icon" src={SearchIcon}></Image>
              </View>
            </View>
          ) : null
        }
        <View style='height:90rpx'></View>
        <View className="main-list">
          {
            dataList.map((item, index) => {
              return item.articleType == 'TEXT' ? (
                <View className="cell-item" key={index} onClick={this.gotoDiscoverDetail.bind(this, index)}>
                  <View className="cell-title">{item.title}</View>
                  <View className="cell-sub-title">{SDUtils.formatDate(item.createTime || 0, 'yyyy-MM-dd HH:mm')}</View>
                  <View className="cell-content">{ item.content }</View>
                  {
                    item.picList.length > 0 ? <View className={`cell-pic_list ${item.picList.length == 4 ? 'cell-pic_list_4' : ''}`}>
                      {
                        item.picList.map((innerItem, innerIndex) => {
                          return (
                            <View className="cell-pic_item" key={innerIndex} onClick={this.previewImage.bind(this, index, innerIndex)}>
                              <Image className="cell-pic_img" src={SDUtils.processImageURL(innerItem.content || '', 435)} mode='aspectFill' lazyLoad />
                            </View>
                          )
                        })
                      }
                    </View> : null
                  }
                </View>
              ) : item.articleType == 'AUDIO' ? (
                <View className="cell-item" key={index} onClick={this.gotoDiscoverDetail.bind(this, index)}>
                  <View className="cell-title">{item.title}</View>
                  <View className="cell-sub-title">2018-09-04 15:30</View>
                  <View className="cell-content">{item.content}</View>
                  <View className='cell-pic_list'>
                    <View className="audio-item">
                      <Image className="audio-left" src={VideoIcon} />
                      <View className="audio-right">
                        <View className="audio-title">品牌化运营、推广、优化</View>
                        <Slider className="audio-slider" value={2} step={0.01} min={0} max={100} blockSize={7}
                                backgroundColor='#E2E2E2' activeColor='#934900' disabled />
                        <View className="audio-bottom">
                          <View className="audio-bottom_item">00:00</View>
                          <View className="audio-bottom_item">{SDUtils.formatDuration(item.audioTime)}</View>
                        </View>
                      </View>
                    </View>
                  </View>
                </View>
              ) : (
                <View className="cell-item" key={index} onClick={this.gotoDiscoverDetail.bind(this, index)}>
                  <View className="cell-title">{item.title}</View>
                  <View className="cell-sub-title">2018-09-04 15:30</View>
                  <View className="cell-content">{item.content}</View>
                  <View className='cell-pic_list'>
                    <View className="video-item">
                      <Image className="video-poster" src={item.videoCoverImage} />
                      <View className="inner-item">
                        <Image className="play-icon" src={PlayIcon} />
                      </View>
                    </View>
                  </View>
                </View>
              )
            })
          }
        </View>


        <SDLoading loading={loading} hasData={hasData} hasMore={hasMore} hideLoading={hideLoading}>
          <CommonEmptyView title='暂无数据' icon={EmptyIcon} mainTop={90} titleColor='#666' />
        </SDLoading>
      </SDBody>
    )
  }

  componentDidMount () {
    this.fetchData(0, true)
  }

  onPullDownRefresh () {
    this.fetchData(0, true, false)
  }

  onReachBottom () {
    const { dataList } = this.state
    this.fetchData(dataList.length)
  }

  fetchData = async (offset: number = 0, refresh: boolean = false, setEmpty: boolean = true) => {
    let { tabBarList, loading, hasMore, hasData, dataList } = this.state
    if (loading || (offset > 0 && !hasMore)) { return }
    if (offset == 0) {
      dataList = []
    }
    const pageData: object = {
      loading: true,
      hasData: true,
      hasMore: true,
      hideLoading: refresh == true
    }
    if (setEmpty) {
      // @ts-ignore
      pageData.dataList = dataList
    }
    await this.setState({
      ...pageData
    })

    try {
      if (refresh) {
        this.tabBarRequestTask = SDUtils.getAbortToken()
        tabBarList = await SDUtils.doGet('/content/wxmini/articleGroup/list',{sortBy: 'group_code:asc'}, this.tabBarRequestTask)
        tabBarList = tabBarList.map((item, _) => {
          return {
            title: item.groupName,
            selected: item.groupCode == this.currentGroupCode,
            code: item.groupCode
          }
        })
        let idx = tabBarList.findIndex(item => item.selected)
        if (idx < 0 && tabBarList.length > 0) {
          tabBarList[0].selected = true
        }
      }

      let selectedTabBar = tabBarList.find(item => item.selected)
      if (selectedTabBar && selectedTabBar.code) {
        this.currentGroupCode = selectedTabBar.code
        this.articleRequestTask = SDUtils.getAbortToken()
        const result = await SDUtils.doGet('/content/wxmini/article/discover', {
          offset: offset,
          limit: 20,
          groupCode: selectedTabBar.code
        }, this.articleRequestTask) || {}
        let items = result.items || []
        items.map(item => {
          item.picList = (item.articleContent || []).filter(innerItem => innerItem.type == 'IMAGE')
          item.content = ((item.articleContent || []).find(innerItem => innerItem.type == 'TEXT') || {}).content || ''
          return item
        })
        dataList = dataList.concat(items)
        hasData = result.total > 0
        hasMore = result.total > dataList.length
      }
    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      setTimeout(() => {
        Taro.stopPullDownRefresh()
        this.setState({
          mainIsLoading: false,
          loading: false,
          hasMore: hasMore,
          hasData: hasData,
          tabBarList: tabBarList,
          dataList: dataList,
          hideLoading: false
        })
      }, 1000)
    }
  }

  // 取消之前网络请求
  cancelPreRequest = async () => {
    this.tabBarRequestTask && this.tabBarRequestTask.abort()
    this.articleRequestTask && this.articleRequestTask.abort()
  }

  switchTabBarIndex = (index: number) => {
    let { tabBarList } = this.state
    if (tabBarList[index].selected) { return }
    tabBarList = tabBarList.map(item => {
      item.selected = false
      return item
    })
    tabBarList[index].selected = true
    let query = Taro.createSelectorQuery()
    query.select(`#tabBar-index${index}`).fields({rect: true, size: true})
    query.select('#menu-bar_ID').scrollOffset()

    query.exec(res => {
      let offsetX = res[1].scrollLeft + res[0].left
      let scrollLeft = offsetX - windowWidth * 0.5 + res[0].width * 0.5
      this.setState({
        scrollLeft: scrollLeft,
        tabBarList: tabBarList
      }, async () => {
        await this.cancelPreRequest()
        this.fetchData()
      })
    })
  }

  previewImage = (index, innerIndex, e) => {
    e.stopPropagation()
    const { dataList } = this.state
    let dataItem = dataList[index]
    let picList = dataItem.picList
    let picItem = picList[innerIndex]

    Taro.previewImage({
      urls: picList.map(item => {
        return item.content
      }),
      current: picItem.content
    })
  }

  gotoSearchPage = () => {
    const { tabBarList } = this.state
    let selectedTabBar = tabBarList.find(item => item.selected) || {}
    SDUtils.jumpTo('/pages/discover/search/index', {
      code: selectedTabBar.code || ''
    })
  }

  gotoDiscoverDetail = (index) => {
    const { dataList } = this.state
    let dataItem = dataList[index]
    SDUtils.jumpTo('/pages/discover/detail/index', {
      articleId: dataItem.articleId
    })
  }
}

export default TabBarDiscoverPage as ComponentClass<PageOwnProps, PageState>
